package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.*;
import com.hualude.roadsign.repository.*;
import com.hualude.roadsign.service.SignalMachineFaultService;
import com.hualude.roadsign.utils.PushUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by pjn on 2017/7/22.
 */
@Service
public class SignalMachineFaultServiceImpl implements SignalMachineFaultService {
    @Resource
    private SignalMachineFaultRepository signalMachineFaultRepository;
    @Resource
    private SignalMachineRepository signalMachineRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private OrgRepository orgRepository;
    @Resource
    private PushHistoryRepository pushHistoryRepository;

    private String strUserIds;

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public DTResponseDto getMachineReportFault4DT(DTRequestDto dtRequestDto, Integer actorId, Integer userId, Integer orgId) throws Exception {
        Integer count;
        List<DTMachineFaultDto> dto4DTs;
        count = signalMachineFaultRepository.getMachineReportFaultCount4DT(actorId, userId, orgId, dtRequestDto.getSearch());
        dto4DTs = signalMachineFaultRepository.getMachineReportFault4DT(dtRequestDto, actorId, userId, orgId);
        for (DTMachineFaultDto dto : dto4DTs) {
            dto.setMachineCheckerName(userRepository.getUserNameByUserId(dto.getMachineCheckerId()));
        }
        DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
        return dtResponseDto;
    }

    public SignalMachineFaultDto getSignalMachineInfo2Fault(Integer signalMachineId) throws Exception {
        SignalMachineFaultDto signalMachineFaultDto;
        signalMachineFaultDto = signalMachineRepository.getSignalMachineInfo2Fault(signalMachineId);
        signalMachineFaultDto.setMachineCreatorName(userRepository.getUserNameByUserId(signalMachineFaultDto.getSignalMachineCreatorId()));
        signalMachineFaultDto.setMachineOrgName(orgRepository.getMainOrgName(signalMachineFaultDto.getSignalMachineOrgId()));
        signalMachineFaultDto.setMachineMainOrgName(orgRepository.getMainOrgName(signalMachineFaultDto.getSignalMachineMainOrgId()));
        signalMachineFaultDto.setSignalMachineId(signalMachineId);
        return signalMachineFaultDto;
    }

    public SignalMachineFaultDto getSignalMachineFaultInfo2Fault(Integer signalMachineId, Integer machineFaultId) throws Exception {
        SignalMachineFaultDto signalMachineFaultDto;
        signalMachineFaultDto = signalMachineRepository.getSignalMachineInfo2Fault(signalMachineId);
        SignalMachineFaultDto machineFault = signalMachineFaultRepository.getSignalMachineFaultInfo2Fault(machineFaultId);
        machineFault.setSignalMachineProvince(signalMachineFaultDto.getSignalMachineProvince());
        machineFault.setSignalMachineCity(signalMachineFaultDto.getSignalMachineCity());
        machineFault.setSignalMachineArea(signalMachineFaultDto.getSignalMachineArea());
        machineFault.setSignalMachineStartRoad(signalMachineFaultDto.getSignalMachineStartRoad());
        machineFault.setSignalMachineEndRoad(signalMachineFaultDto.getSignalMachineEndRoad());
        machineFault.setSignalMachineLongitude(signalMachineFaultDto.getSignalMachineLongitude());
        machineFault.setSignalMachineLatitude(signalMachineFaultDto.getSignalMachineLatitude());
        machineFault.setMachineOrgId(signalMachineFaultDto.getSignalMachineOrgId());
        machineFault.setMachineMainOrgId(signalMachineFaultDto.getSignalMachineMainOrgId());
        UserDto userDto = userRepository.getUserById(machineFault.getMachineCreatorId());
        machineFault.setMachineCreatorName(userDto.getUserName());
        machineFault.setMachineCreatorPhone(userDto.getUserMobile());
        return machineFault;
    }

    @Transactional
    public Integer updateSignalMachineFault(Integer machineFaultId, Integer machineLevel, Integer machineType, String machinePhoto, String machineReason, Double machineMoney) throws Exception {
        return signalMachineFaultRepository.updateSignalMachineFault(machineFaultId, machineLevel, machineType, machinePhoto, machineReason, machineMoney);
    }

    @Transactional
    public Integer deleteMachineFaultByIds(String machineFaultIds) throws Exception {
        String[] machineFaultIdArray = machineFaultIds.split(",");
        int i = 0;
        for (i = 0; i < machineFaultIdArray.length; i++) {
            signalMachineFaultRepository.deleteMachineFaultByIds(Integer.parseInt(machineFaultIdArray[i]));
        }
        return i;
    }

    public List<SignalMachineFaultDto> getMachineCoordinate4Map(Integer orgId, Integer actorId) throws Exception {
        return signalMachineRepository.getMachineCoordinate4Map(orgId, actorId);
    }

    public List<SignalMachineFaultDto> getMachineEnergyByXY(String longitude, String latitude) throws Exception {
        return signalMachineRepository.getMachineEnergyByXY(longitude, latitude);
    }

    public DTResponseDto getMachineFaultReport4DT(DTRequestDto dtRequestDto, Integer actorId, Integer orgId, String signalMachineStartRoad, String signalMachineEndRoad) throws Exception {
        if (signalMachineStartRoad.equals("") && signalMachineEndRoad.equals("")) {
            return new DTResponseDto(dtRequestDto.getDraw(), 0, 0, "");
        } else {
            Integer count = signalMachineRepository.getMachineFaultReportCount4DT(dtRequestDto.getSearch(), actorId, orgId, signalMachineStartRoad, signalMachineEndRoad);
            List<DTMachineFaultDto> dto4DTs = signalMachineRepository.getMachineFaultReport4DT(dtRequestDto, actorId, orgId, signalMachineStartRoad, signalMachineEndRoad);
            for (DTMachineFaultDto dto : dto4DTs) {
                List<SignalMachineFaultDto> signalMachineFaultDtos = signalMachineFaultRepository.getMachineFaultIsReport(dto.getSignalMachineId());
                Integer result = 1;
                if (signalMachineFaultDtos.size() != 0) {
                    Integer mainCheck = signalMachineFaultDtos.get(0).getMachineMainCheck();
                    Integer check = signalMachineFaultDtos.get(0).getMachineCheck();
                    Integer status = signalMachineFaultDtos.get(0).getMachineMaintenanceStatus();
                    if (status == 2) {
                        result = 1;//维修完成
                    } else if (mainCheck == -1 || check == -1) {
                        result = 1;//
                    } else {
                        result = 0;
                    }
                }
                dto.setReportStatus(result);
            }
            DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
            return dtResponseDto;
        }
    }


    public Integer getMachineFaultIsReport(Integer signalMachineId) throws Exception {
        List<SignalMachineFaultDto> signalMachineFaultDtos = signalMachineFaultRepository.getMachineFaultIsReport(signalMachineId);
        Integer result = 1;
        if (signalMachineFaultDtos.size() != 0) {
            Integer mainCheck = signalMachineFaultDtos.get(0).getMachineMainCheck();
            Integer check = signalMachineFaultDtos.get(0).getMachineCheck();
            Integer status = signalMachineFaultDtos.get(0).getMachineMaintenanceStatus();
            if (status == 2) {
                result = 1;//维修完成
            } else if (mainCheck == -1 || check == -1) {
                result = 1;//
            } else {
                result = 0;
            }
        }
        return result;
    }


    public Integer reportMachineFault(final Integer signalMachineId, Integer machineCreatorId, Integer machineLevel, Integer machineType,
                                      String machinePhoto, String machineReason, Double machineMoney, final Integer machineOrgId, Integer machineMainOrgId) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        if (machineMoney == null)
            machineMoney = 0.0;
        SignalMachineFaultDto insertDto = new SignalMachineFaultDto();
        insertDto.setSignalMachineId(signalMachineId);
        insertDto.setMachineCreatorId(machineCreatorId);
        insertDto.setMachineLevel(machineLevel);
        insertDto.setMachineType(machineType);
        insertDto.setMachineTime(df.format(new Date()));
        insertDto.setMachinePhoto(machinePhoto);
        insertDto.setMachineReason(machineReason);
        insertDto.setMachineMoney(machineMoney);
        insertDto.setMachineOrgId(machineOrgId);
        insertDto.setMachineMainOrgId(machineMainOrgId);

        List<UserDto> userDtos = userRepository.getUserIdsByOrgIdAndActorId(machineOrgId, 3);
        final String msg = "信号机 NO：" + signalMachineId + " 待审核";
        strUserIds = "";
        for (UserDto userDto : userDtos) {
            strUserIds += userDto.getUserId().toString() + ",";
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!strUserIds.equals("")) {
                        strUserIds = strUserIds.substring(0, strUserIds.length() - 1);
                        PushUtil.sendPushToUser(strUserIds, msg);
                        PushHistoryDto pushHistoryDto = new PushHistoryDto(machineOrgId, 3, msg, formatter.format(new Date()),3);
                        pushHistoryRepository.save(pushHistoryDto.toBean());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return signalMachineFaultRepository.save(insertDto.toBean()).getMachineFaultId();
    }

    public List<String> getStartRoad(String roadName, Integer actorId, Integer orgId) throws Exception {
        return signalMachineRepository.getStartRoad(roadName, actorId, orgId);
    }

    public List<String> getSectionByStartRoad(String roadName, Integer actorId, Integer orgId) throws Exception {
        return signalMachineRepository.getSectionByStartRoad(roadName, actorId, orgId);
    }

    public List<SignalMachineFaultDto> getMachineFaultList4App(Integer orgId, String actorIds, Integer faultStatus, Integer count, Integer size) throws Exception {
        return signalMachineFaultRepository.getMachineFaultList4App(orgId,actorIds,faultStatus,count,size);
    }
}
